<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" >
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <!--
      :data="products"  - 列表数据 - 数组
      highlight-current-row - 当前行高亮
      v-loading="listLoading" - 加载框/忙等框
      @selection-change="selsChange" - 选项改变时触发
      style="width: 100%;" - 宽度
      :row-key="getRowKey"
      在使用 reserve-selection 功能与显示树形数据时，该属性是必填的
    -->
    <el-table :data="products" highlight-current-row :row-key="getRowKey" v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="服务名称" width="150">
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" width="60">
      </el-table-column>
      <el-table-column prop="saleprice" label="市场价" width="60">
      </el-table-column>
      <el-table-column prop="salecount" label="销售数量" width="80">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="60">
        <template scope="scope">
          <span v-if="scope.row.state==1" style="color: #42d885">上线</span>
          <span v-else style="color: #666666">下线</span>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="上线时间" width="150">
      </el-table-column>
      <el-table-column prop="onsaletime" label="下线时间" width="150" >
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="150" >
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleSave(scope.$index, scope.row)" >编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--批量删除及分页栏-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :current-page="currentPage" :total="totals" style="float:right;">
      </el-pagination>
    </el-col>
    <!-- 添加修改 -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="市场价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="服务资源">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastDfs/"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.productDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor v-model="saveForm.productDetail.intro" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="预约须知" prop="adoptNotice" >
          <quill-editor v-model="saveForm.productDetail.orderNotice" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
// 引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; // 调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config.js';

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      quillOption: quillConfig,
      // 列表数据，回调函数中给它赋值
      products: [],
      // 加载框
      listLoading: false,
      // 当前页
      currentPage: 1,
      // 每页显示的条数
      pageSize: 10,
      //总数量
      totals: 0,
      filters: {
        name: ''
      },
      keyword:'',
      page: 1,
      sels: [],//列表选中列
      //4.添加和修改的数据
      saveFormVisible: false,//编辑界面是否显示
      title:"",
      // 加载框
      saveLoading: false,
      //验证规则
      saveFormRules: {
        name: [
          { required: true, message: '请输入服务名称', trigger: 'blur' }
        ]
      },
      // 对话框的数据
      saveForm: {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        resources: '',
        salecount: null,
        productDetail:{  // 与后端实体类一致
          intro: '',
          orderNotice: ''
        }
      },
      // 上传图片时，用于保存图片的
      fileList: []
    }
  },
  methods: {
    // 组装参数
    getProducts() {
      let paras = {
        currentPage:this.currentPage,
        pageSize:this.pageSize,
        keyword:this.keyword
      };
      // 显示加载框
      this.listLoading = true;
      // 使用axios发送分页请求
      this.$http.post("/product",paras).then(res=>{
        this.products = res.data.data;
        this.totals = res.data.totals;
        this.listLoading = false;
      }).catch(res=>{
        this.$message.error("系统繁忙，请稍后重试");
      });

    },
    // 分页查询 - 点击分页栏触发方法
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getProducts();
    },
    // 高级查询
    keywordQuery(){
      // 将当前页置为1，防止出现查询错误
      this.currentPage = 1;
      this.getProducts();

    },
// 删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/product/"+ row.id).then(res=>{
          // 成功后处理
          if (res.data.success) {
            let totalPage = Math.ceil(this.totals/this.pageSize)
            /*if (this.currentPage == totalPage && (this.totals-1)%this.pageSize==0 && this.currentPage!=1){
              this.currentPage = this.currentPage -1;
        }*/
            if (this.products.length == 1 && this.currentPage != 1) {
              this.currentPage = this.currentPage -1
            }
            this.getProducts();
          } else {
            this.$message.error("系统繁忙，请稍后重试！！");
          }
          // 关闭加载框
          this.listLoading = false;
        }).catch(res=>{
          this.$message.error("系统繁忙，请稍后重试！！");
        })
      }).catch(() => {

      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/product",ids).then(res=>{
          if (res.data.success) {
            this.currentPage = 1;
            this.getProducts();
          } else {
            this.$message.error("系统繁忙......[500]")
          }
          this.listLoading = false;
        }).catch(res=> {
          this.$message.error("系统繁忙......[400，404]")
        })
      }).catch(() => {
      });
    },

    //显示编辑界面
    handleSave: function (index, row) {
      this.title = "编辑";
      // 克隆：修改对话框填入的数据提交前不影响列表的数据
      this.saveForm = Object.assign({}, row);
      // 清空fileList的数据
      this.fileList = [];
      if(this.saveForm.resources){ //如果有值
        let paths = this.saveForm.resources.split(",");
        for(var i = 0;i<paths.length;i++){
          this.fileList.push({"url":"http://123.207.27.208"+paths[i]})
        }
      }
      this.saveFormVisible = true;
    },
    // 点击新增按钮弹出对话框
    handleAdd: function () {
      this.title = "新增";
      this.saveForm = {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        resources: '',
        productDetail:{  // 与后端实体类一致
          intro: '',
          orderNotice: ''
        }
      };
      // 清空fileList的数据
      this.fileList = [];
      // 弹出对话框
      this.saveFormVisible = true;
    },
    // 新增或者修改
    saveSubmit: function () {
      // 表单验证，全部通过才会返回true
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;

            this.$http.put("/product",this.saveForm).then(res=>{
              if (res.data.success) {
                this.getProducts();
              } else {
                this.$message.error("系统繁忙......[500]")
              }
              this.saveLoading = false;
            }).catch(res=>{
              this.$message.error("系统繁忙......[400，404]");
              this.saveLoading = false;
            })
            // 关闭对话框
            this.saveFormVisible = false;

          });
        }
      });
    },
    // 用来区分每一个对象的唯一标识
    getRowKey(row) {
      return row.id;
    },
    // 图片上传成功之后的回调
    handleSuccess(response, file, fileList) {
      let filePath = response.resultObj;
      // 1.对resources的处理 - 添加到数据库  有值返回true
      if (this.saveForm.resources) {
        this.saveForm.resources = this.saveForm.resources + "," +filePath;
      } else {
        this.saveForm.resources = filePath;
      }
      // 2.对fileList的处理 - 前端显示图片的
      // 先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
      this.fileList = [];
      if (this.saveForm.resources) {
        var arr = this.saveForm.resources.split(",");
        for (var i = 0;i<arr.length;i++){
          var item = arr[i];
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }
    },
    // 点击删除图片之后对resources【操作数据库】和fileList【前台显示】做处理，并且调用删除接口删除图片
    handleRemove(file, fileList) {
      let filePath = file.url.substring(file.url.indexOf("/group1"));
      // 调用删除接口
      this.$http.delete("/fastDfs?path="+filePath).then(res=>{
        if(res.data.success){
          this.$message.success("删除成功");
        }else{
          this.$message.error("删除失败");
        }
      })
      // 对resources的处理：需要从数组中删除某一个元素
      if (this.saveForm.resources) {
        var paths = this.saveForm.resources.split(",");
        for (var i = 0;i<paths.length;i++){
          // 找到需要删除的图片，图片索引为i
          if (filePath == paths[i]) {
            paths.splice(i,1);
          }
          break;
        }
        this.saveForm.resources = paths.join(",");
      }
      // 对fileList的处理
      this.fileList = [];
      if (this.saveForm.resources) {
        let arr = this.saveForm.resources.split(",");
        for (var i = 0;i<arr.length;i++){
          var item = arr[i];
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }
    },

    // 服务上架
    onsale() {
      var ids = this.sels.map(item => item.id);
      if (!ids || ids.length == 0) {
        this.$message.error("请勾选要上架的商品");
        return;
      }
      this.$confirm('确认要上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => { //点击确定走这里
        this.$http.post("/product/onsale", ids).then(res => {
          if (res.data.success) {
            this.getProducts();
          } else {
            this.$message.error("系统异常，上架失败");
          }
        }).catch(res => {
          this.$message.error("系统异常，请稍后重试!!!400,404");
        })
      }).catch(() => {
      });
    },
    // 服务下架
    offsale() {
      var ids = this.sels.map(item => item.id);
      if (!ids || ids.length == 0) {
        this.$message.error("请勾选要下架的商品");
        return;
      }
      this.$confirm('确认要上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => { //点击确定走这里
        this.$http.post("/product/offsale", ids).then(res => {
          if (res.data.success) {
            this.getProducts();
          } else {
            this.$message.error("系统异常，下架失败");
          }
        }).catch(res => {
          this.$message.error("系统异常，请稍后重试!!!400,404");
        })
      }).catch(() => {
      });
    }

  },
  mounted() {
    this.getProducts();
  },
}

</script>

<style scoped>

</style>
